<template>
    <div class="app-container">
      <el-card class="box-card">
        <div class="flex justify-between items-center mb-4">
            <span>已上传歌曲（{{total}}）首</span>
            <div>
              <el-button type="danger" @click="handleDeleteAll">删除歌曲</el-button>
              <el-button type="success" @click="handleCreate">&emsp;上传歌曲&emsp;</el-button>
            </div>
        </div>
        <div class="flex justify-between">
          <div class="flex flex-wrap">
            <div>
              <span>歌曲名称：</span>
              <el-input
                  v-model.number="listQuery.song_name"
                  class="marginRB10"
                  clearable
                  placeholder="请输入歌曲名称"
                  style="width: 200px"
              ></el-input>
            </div>
            <div>
              <span>用户ID：</span>
              <el-input
                  v-model.number="listQuery.user_id"
                  class="marginRB10"
                  clearable
                  placeholder="请输入用户ID"
                  style="width: 200px"
              ></el-input>
            </div>
            <div>
              <span>用户昵称：</span>
              <el-input
                  v-model.number="listQuery.nickname"
                  class="marginRB10"
                  clearable
                  placeholder="请输入用户昵称"
                  style="width: 200px"
              ></el-input>
            </div>
            <div>
              <span>开始时间：</span>
              <el-date-picker v-model="listQuery.start_time" class="marginRB10" placeholder="开始时间"
                              type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </div>
            <div>
              <span>结束时间：</span>
              <el-date-picker v-model="listQuery.end_time" class="marginRB10" placeholder="结束时间"
                              type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </div>
            <el-button
              class="marginRB10"
              icon="el-icon-search"
              type="primary"
              @click="searchSubmit"
            >搜索
            </el-button>
            <el-button class="marginRB10" @click="resetSubmit">重置</el-button>
          </div>
        </div>
        <div v-loading="listLoading" class="item">
          <el-table ref="dataList"
                    :data="menuList"
                    border
                    @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection"></el-table-column>
            <el-table-column label="歌曲名称" prop="name"></el-table-column>
            <el-table-column label="歌曲内容" min-width="100px" prop="url">
              <template slot-scope="scope">
                <audio :src="scope.row.url" controls></audio>
              </template>
            </el-table-column>
            <el-table-column label="歌手" prop="singer"></el-table-column>
            <el-table-column label="上传用户" prop="user.nickname">
              
              <template slot-scope="scope">
                {{scope.row.user_id ? scope.row.user_id : '摩卡moka'}}
              </template>
            </el-table-column>
            <el-table-column label="上传用户ID" prop="user.user_code"></el-table-column>
            <el-table-column label="大小(Mb)" prop="size"></el-table-column>
            <el-table-column label="播放次数" prop="play_count"></el-table-column>
            <el-table-column label="上传时间" prop="created_at"></el-table-column>
            <el-table-column label="审核通过时间" prop="audit_at"></el-table-column>
            <el-table-column label="操作" width="200px">
              <template slot-scope="scope">
                <el-button icon="el-icon-delete" plain
                           size="mini" type="danger" @click="handleDelete(scope.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <cus-pagination :limit.sync="listQuery.perPage" :page.sync="listQuery.page" :total="total"
                          @pagination="getList"
          />
        </div>
      </el-card>
      <!-- 删除弹框 -->
      <el-dialog :visible.sync="deleteDialogVisible" title="确定删除吗?" width="435px">
        <div>
          提示：您已选择
          <span v-for="(item, index) in multipleSelection" :key="index">
            <span v-if="index < 3">{{item.name}},</span>
          </span>
          ...多条数据，是否确认删除？
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmDelete">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 上传弹窗 -->
      <el-dialog
        title="上传歌曲"
        :visible.sync="visibleDialog"
        width="30%"
        @close="resetForm">
        <el-form :model="formData" ref="form" :rules="rules" label-width="80px" :inline="false" size="normal">
          <el-form-item label="歌曲名称" prop="name">
            <el-input v-model="formData.name" maxlength="20" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="歌手" prop="singer">
            <el-input v-model="formData.singer" maxlength="20" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="上传歌曲" prop="url">
            <div class="awardBox">
                <div class="awardInfo">
                    <!-- <audio v-if="formData.content" :src="formData.content" class="avatar"></audio> -->
                    <el-upload
                        ref="upload"
                        :http-request="customizeUpload"
                        :on-success="handlePictureSuccess1"
                        :before-remove="beforeRemove"
                        :on-remove="handleRemove"
                        action=""
                        class="upload-demo"
                        :limit="1"
                        :file-list="fileList"
                        :before-upload="beforeUpload"
                        :on-change="handleChange"
                    >
                        <el-button v-if="!formData.url" size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">大于512K且不超过20M，支持MP3格式</div>
                        <el-progress v-if="showProgress" slot="tip" :text-inside="true" :stroke-width="18" :percentage="percentage"></el-progress>
                    </el-upload>
                    <!-- <span class="closeIcon" @click="handlePictureRemove1"><i class="el-icon-delete"></i></span> -->
                </div>
            </div>
          </el-form-item>
          <el-form-item label="歌曲类型" prop="type">
            <el-select v-model="formData.type" placeholder="请选择" clearable filterable>
              <el-option v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="歌曲封面" prop="cover">
            <div class="awardBox awardBox2">
                <div class="awardInfo" :class="{'hide_box': formData.cover, 'show_box': !formData.cover}" style="width: 200px;">
                    <img v-if="formData.cover" :src="formData.cover" class="avatar" />
                    <el-upload
                        v-else
                        ref="upload"
                        :auto-upload="true"
                        :http-request="customizeUpload"
                        :on-success="handlePictureSuccess2"
                        action=""
                        class="upload-demo"
                        :limit="1"
                        list-type="picture-card"
                    >
                        <i slot="default" class="el-icon-plus"></i>
                    </el-upload>
                    <span class="closeIcon" @click="handlePictureRemove2"><i class="el-icon-delete"></i></span>
                </div>
            </div>
          </el-form-item> -->
          
          <el-form-item label="歌曲大小">
            <el-input v-model="formData.size" disabled></el-input>
          </el-form-item>
          <el-form-item label="歌曲时长">
            <el-input v-model="formData.send" disabled></el-input>
          </el-form-item>
          
        </el-form>
        <el-checkbox v-model="checked">我已认真阅读并同意以下<span @click.prevent="rulesDialogVisible = true" style="color: #a0cfff;">《歌曲上传分享服务规则》</span></el-checkbox>
        <span slot="footer">
          <el-button @click="visibleDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :disabled="!checked">确认上传</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="享服务规则"
        :visible.sync="rulesDialogVisible"
        width="60%">
        <div class="rules">
          <h2>歌曲上传分享服务规则</h2>
          <p>本规则被视为<a style="color: #a0cfff;" href="https://moka-web.imechos.com/common/moka-h5/protocol/user-agreement" target="_blank">《Moka摩卡用户协议》</a>的附件，如本规则与 
            <a style="color: #a0cfff;" href="https://moka-web.imechos.com/common/moka-h5/protocol/user-agreement" target="_blank">《Moka摩卡用户协议》</a>存在冲突的，以本规则为准。</p>
          
          <h5>您在使用歌曲服务前详细阅读本服务规则，理解并同意：</h5>
          <p>1 沈阳沁音科技有限公司仅提供信息存储空间网络技术服务，您承诺对您所上传、分享的内容应有合法来源，并保证相关内容为您所有或您已获得权利人的授权，不得上传、分享任何违法或侵害第三方合法权益的内容，不得利用Moka摩卡作出任何违反法律或侵害任何第三方合法权益的行为。</p>
          <p>2 您上传的内容中，不得含有：</p>
          <p>1) 反对宪法所确定的基本原则的；</p>
          <p>2) 违反国家法律、危害国家安全统一、社会稳定、公序良俗、社会公德以及侮辱、诽谤、淫秽或含有任何性或性暗示的、暴力的内容；</p>
          <p>3) 损害国家荣誉和利益的；</p>
          <p>4) 煽动民族仇恨、民族歧视、破坏民族团结的；</p>
          <p>5) 破坏国家宗教政策，宣扬邪教和封建迷信的；</p>
          <p>6) 散布谣言，扰乱社会秩序，破坏社会稳定的；</p>
          <p>7) 散布淫秽、色情、赌博、暴力、凶杀、恐怖或者教唆犯罪的；</p>
          <p>8) 侵害他人名誉权、肖像权、知识产权、商业秘密等合法权利的内容；</p>
          <p>9) 煽动非法集会、结社、游行、示威、聚众扰乱社会秩序的；</p>
          <p>10) 以非法民间组织名义活动的；</p>
          <p>11）骚扰、广告信息及垃圾信息；</p>
          <p>12) 含有虚假、有害、胁迫、侵害他人隐私、骚扰、侵害、中伤、粗俗、猥亵、或其它道德上令人反感的内容。</p>
          <p>13）其他违反法律法规、政策及公序良俗、社会公德或干扰音频作品正常运营和侵犯其他用户或第三方合法权益内容的信息。</p>
          <p>3 战歌列表仅限上传、分享音频形式的音乐，不得上传或分享以音频形式存储的各类网络剧、网络电影、新闻节目、纪录片、专题片、综艺节目等视听节目，亦不得上传网民上传的自制时政类视听新闻节目。</p>
          <p>4 您将相关内容上传、分享至Moka摩卡后，即视为同意Moka摩卡及Moka摩卡用户使用和传播该等内容。</p>
          <h1>5 请您注意：当您选择“扫描本地歌曲”时，即授权Moka摩卡对您的手机本地文件进行音乐文件的扫描，请您注意对您的隐私及不希望被扫描的文件采取措施，否则视为同意扫描。</h1>
          <p>6 您将对因您的上传、分享行为导致的纠纷承担全部法律责任，给任何第三方造成损害的，您应当独立承担责任；Moka摩卡因此遭受损失的，您也应当一并赔偿。</p>
          <p>7 如果发现或收到他人举报您发布的信息或内容违反前述约定或Moka摩卡其它规则及相关协议约定的，Moka摩卡有权进行独立判断并采取技术手段予以删除、屏蔽或断开链接。同时，Moka摩卡有权根据行为性质，采取包括但不限于暂停或终止服务，限制、冻结或您的Moka摩卡账号的使用，追究法律责任等措施。</p>
          <p>8 如果您违反了本规则约定或相关法律规定，相关国家机关或机构可能会对您提起诉讼、罚款或采取其他制裁措施，并要求Moka摩卡给予协助。造成损害的，您应依法予以赔偿，Moka摩卡不承担任何责任。</p>
          <p>9 您确认Moka摩卡已提供投诉渠道，并已阅读并知悉Moka摩卡公示的所有维权投诉规则和指引，知悉投诉渠道入口。您将自行决定是否就您受到的权利侵害进行投诉，并承诺不得滥用投诉行为侵害其他用户的合法权利或作出其他违规违法行为。</p>
        </div>
        <span slot="footer">
          <el-button type="primary" @click="rulesDialogVisible = false">确认</el-button>
        </span>
      </el-dialog>
      
      
    </div>
</template>
  
<script>
  import { roomSongDel, roomSongList, roomSongSave } from '@/api/musicManagement'
  
  export default {
    data() {
      return {
        rulesDialogVisible: false,
        checked: false,
        showProgress: false,
        percentage: 0,
        row_id: 0,
        visibleDialog: false,
        formData: {
          type: undefined, //类型  1原创 2伴奏
          user_id: undefined, //用户id，没有用户id传0
          name: undefined,
          url: undefined,
          cover: undefined, //封面
          singer: undefined, //歌手
          size: undefined, //歌曲大小
          send: undefined, //总时长
        },
        rules: {
          singer: [{ required: true, message: '请输入歌手名称', trigger: 'change' }],
          name: [{ required: true, message: '请输入歌曲名称', trigger: 'change' }],
          url: [{ required: true, message: '请上传歌曲', trigger: 'change' }],
          type: [{ required: true, message: '请选择', trigger: 'change' }],
        },
        fileList: [],
        options: [
          {
            value: 1,
            label: '原创'
          },
          {
            value: 2,
            label: '伴奏'
          },
        ],
        deleteDialogVisible: false,
        listLoading: false,
        menuList: [],
        listQuery: {
          page: 1,
          perPage: 10,
          song_name: undefined,
          user_id: undefined,
          nickname: undefined,
          start_time: undefined,
          end_time: undefined
        },
        total: 0,
        // 勾选内容
        multipleSelection: [],
        // 要删除的内容的ids
        dataIds: '',
        skippArr: [],
        timer: ''
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        for (let key in this.listQuery) {
          this.listQuery[key] = this.listQuery[key] === '' ? undefined : this.listQuery[key] == 0 ? 0 : this.listQuery[key]
        }
        roomSongList(this.listQuery).then(response => {
          this.menuList = response.data.data
          this.total = response.data.total
          this.listLoading = false
          // this.confirmBtn = false
        })
      },
      searchSubmit() {
        this.listQuery.page = 1
        this.getList()
      },
      // 点击重置
      resetSubmit() {
        this.listQuery = {
          page: 1,
          perPage: 10,
          song_name: undefined,
          user_id: undefined,
          nickname: undefined,
          start_time: undefined,
          end_time: undefined
        }
        this.getList()
      },
      // 点击新增
      handleCreate() {
        this.resetForm()
        this.visibleDialog = true
      },
      // 重置表单内容
      resetForm() {
        this.$nextTick(() => {
          if (this.$refs['form'] !== undefined) {
            this.$refs['form'].resetFields()
          }
          this.cityList = []
          this.formData = {
            type: undefined, //类型  1原创 2伴奏
            user_id: undefined, //用户id，没有用户id传0
            name: undefined,
            url: undefined,
            cover: undefined, //封面
            singer: undefined, //歌手
            size: undefined, //歌曲大小
            send: undefined, //总时长
          }
          this.fileList = []
        })
      },
      submitForm() {
  
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.formData.user_id = 0
            roomSongSave(this.formData).then(response => {
              if (response.code === 200) {
                this.getList()
                this.visibleDialog = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                })
              }
            })
          } else {
            return false
          }
        })
      },
      // 勾选
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      // 点击单个删除
      handleDelete(row) {
        this.$confirm('此操作不可恢复，是否继续删除？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {

          roomSongDel({
            ids: String(row.id)
          }).then(res => {
                if(res.code === 200) {
                    this.$message({
                        type: 'success',
                        message: '操作成功'
                    })
                }
                this.getList()
            })
        }).catch(() => {
            this.$message({
                type: 'info',
                message: '已取消'
            });
        });
      },
      // 点击批量删除
      handleDeleteAll() {
        if (this.multipleSelection.length === 0) {
          this.$message({
            message: '请先勾选要删除的内容',
            type: 'warning'
          })
          return
        } else if (this.multipleSelection.length !== 0) {
          let ids = ''
          for (let key in this.multipleSelection) {
            ids += `${this.multipleSelection[key].id},`
          }
          ids = ids.substring(0, ids.length - 1)
          this.dataIds = { ids: ids }
        }
        if(this.multipleSelection.length === 1) {
          this.handleDelete(this.multipleSelection[0])
        }else {
          this.deleteDialogVisible = true
        }
      },
      // 确定删除
      confirmDelete() {
        
        roomSongDel(this.dataIds).then(response => {
          if (response.code === 200) {
            this.getList()
            this.deleteDialogVisible = false
            this.$notify({
              type: 'success',
              message: '操作成功',
            })
          }
        })
      },
      handlePictureSuccess1(response, file, fileList) {
          console.log(response, file, fileList)
          this.formData.url = this.ossLastImgUrl
          this.fileList = [
              {
                  url: this.ossLastImgUrl,
                  name: file.name
              }
          ]
          this.formData.size = (file.size / 1024 / 1024).toFixed(2)
          var content = file.raw
          var that = this
          console.log(11)
          var url = URL.createObjectURL(content);//获取录音时长
          var audioElement = new Audio(url);//audio也可获取视频的时长
          var duration;
          console.log(22)
          audioElement.addEventListener("loadedmetadata", function (_event) {
              duration = audioElement.duration.toFixed(2);
              console.log(duration);
              that.$set(that.formData, 'send', duration)
              console.log('duration',that.formData.send,duration)
          });
          this.percentage = 100
      },
      beforeRemove(file, fileList) {
          this.fileList = []
          this.formData.url = undefined
      },
      handleRemove(file, fileList) {
          this.fileList = []
          this.formData.url = undefined
          this.formData.send = undefined
          this.formData.size = undefined
      },
      handlePictureRemove1() {
          this.fileList = []
          this.formData.url = undefined
      },
      handlePictureSuccess2() {
          this.formData.cover = this.ossLastImgUrl
      },
      handlePictureRemove2() {
          this.formData.cover = undefined
      },
      beforeUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 20;
        const isDt2M = file.size / 1024 > 512;
        const isMP3 = file.type === 'audio/mpeg'
        console.log('beforeUpload',file)
        if(!isDt2M) {
          this.$message.error('上传歌曲大小不能小于 512KB!');
          this.showProgress = false
          this.percentage = 0
        }
        if (!isLt2M) {
          this.$message.error('上传歌曲大小不能超过 20MB!');
          this.showProgress = false
          this.percentage = 0
        }
        if(!isMP3) {
          this.$message.error('只支持MP3格式!');
          this.showProgress = false
          this.percentage = 0
        }
        return isDt2M && isLt2M && isMP3;
      },
      handleChange(file, fileList) {
        console.log(file.status)
        if(file.status === 'ready') {
          this.showProgress = true
          this.timer = setInterval(() => {
            this.percentage += 1 
            if(this.percentage === 95) {
              clearInterval(this.timer)
              return
            }
          }, 20)
        }else {
          clearInterval(this.timer)
          this.percentage = 100
          setTimeout(() => {
            this.showProgress = false
          }, 200);
        }
      }
    }
  }
</script>
  
<style scoped lang="scss">
  ::v-deep{ 
    .el-progress-bar__innerText {
      color: #ffffff !important;
    }
    .awardBox {
      .el-upload-list__item {
          margin-right: 1em !important;
          width: 200px;
      }

    }

}

.awardBox {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    .awardInfo {
        margin-right: 10px;
        border-radius: 4px;
        position: relative;
        overflow: hidden;
        
        display: flex;
        align-items: center;
        justify-content: center;

        .closeIcon {
            position: absolute;
            top: 0;
            bottom: 0;
            right: 0;
            left: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 10px;
            background: rgba(0,0,0,.6);
            color: #ffffff;
            overflow: hidden;
            cursor: pointer;
            font-size: 18px;
            opacity: 0;
            z-index: 0;
        }
    }
    .hide_box:hover {
        .closeIcon {
            opacity: 1;
            z-index: 1;
        }
    }
    .show_box {
        .closeIcon {
            opacity: 0;
            z-index: -1;
        }
    }
}
  
</style>
  